package org.fyp.synchrona.twitter.service;


import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.fyp.synchrona.core.info.impl.ICommonDataObject;
import org.fyp.synchrona.service.IService;
import org.fyp.synchrona.twitter.service.util.Update;
import org.fyp.synchrona.util.IAccount;
import org.fyp.synchrona.util.IUpdate;




import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

public class TwitterService implements IService{

	
	private String serviceName = "Twitter";

	public String userName;

	public String password;
	
	static final Logger logger = Logger.getLogger(TwitterService.class);
	
	public void executeTask() {
		
		
	}

	
	public void startService(IUpdate updateObj) {
		
		logger.info("[TWITTER] ######################Information from twitter Service########################");
		
		getuserNamePassword(updateObj.getAccount());
		logger.info("[TWITTER] update type ::"+updateObj.getUpdateType());
		if(updateObj.getUpdateType()=="STS"){
			
			logger.info("[TWITTER] -------------------------UPDATE Received is Status Message----------------");
			logger.info(updateObj.getCdo().getSTATUS());
			logger.info("[TWITTER] username ::"+userName);
			logger.info("[TWITTER] password ::"+password);
			updateStatus(updateObj,userName,password);
			
		}else if(updateObj.getUpdateType()=="PROFILE"){
			
			logger.info("[TWITTER] -------------------------UPDATE Received is Profile Update----------------");
			logger.info("[TWITTER] username ::"+userName);
			logger.info("[TWITTER] password ::"+password);
			try {
				profileUpdate(updateObj, userName , password );
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		logger.info("[TWITTER] ######################End Information from Twitter Service########################");
		
		
	}
	
	private void getuserNamePassword(List<IAccount> account) {

		IAccount element= null;
		Iterator i = account.listIterator();

		logger.info("[TWITTER] _+_+_+_+_+_+_+_+_+_+_+_+_+update data_+_+_+_+_+_+_+_+_+_+_+_+_+_");
		while(i.hasNext()) {
			
			element =  (IAccount) i.next(); 
			logger.info("[TWITTER] ++++++++++++++++++++++++service name+++++++++++++++++++++++++++");
		
			logger.info("[TWITTER] servicename ::"+element.getServiceName());
			if(element.getServiceName().equals(serviceName)){
				this.userName = element.getUserName();
				this.password = element.getPassword();
				break;
			}
			logger.info("[TWITTER] ++++++++++++++++++++++++user name+++++++++++++++++++++++++++");
			logger.info("[TWITTER] username ::"+element.getUserName());
			logger.info("[TWITTER] ++++++++++++++++++++++++password+++++++++++++++++++++++++++");
			logger.info("[TWITTER] password ::"+element.getUserName());
			
		} 
		
	}
	
	public static void main(String arg[]){
		IUpdate updateObj = new Update();
		ICommonDataObject cdo = new CommonDataObject();
		//cdo.setBIO("biooooooooooooooooaa");
		//cdo.setCITY("mataleeeeaaa");
		cdo.setUSER_NAME("usernametestii");
		updateObj.setCdo(cdo);
		updateObj.setUpdateType("PROFILE");
		//updateObj.setUser_name("synchrona");
		//updateObj.setUser_password("pass123");
		new TwitterService().startService(updateObj);
		
	}
	
	public  void profileUpdate(IUpdate updateObj,String userName, String password) throws Exception {
    	
    	String web = null;
    	String location = null;
    	String name = null;
    	String description = null;    	
           	
        URL url = new URL("http://api.twitter.com/1/account/update_profile.xml");
        URLConnection connection = url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        String authorization = userName + ":" + password;
        Base64 encoder = new Base64();
        String encoded = new String(encoder.encodeBase64(authorization.getBytes())).trim();
        connection.setRequestProperty("Authorization", "Basic " + encoded);

        OutputStreamWriter out = new OutputStreamWriter(
                connection.getOutputStream());
        //"name=" + name +
        if(updateObj.getCdo().getWEBSITE()!=null){
        	logger.info("[TWITTER] website ::"+updateObj.getCdo().getWEBSITE());
    		web = URLEncoder.encode(updateObj.getCdo().getWEBSITE(), "UTF-8");
    		out.write("&url="+web);
    	}
    	if(updateObj.getCdo().getCITY()!=null){
    		logger.info("[TWITTER] city ::"+updateObj.getCdo().getCITY());
    		location = URLEncoder.encode(updateObj.getCdo().getCITY(), "UTF-8");
    		out.write("&location="+location);
    	}
    	if(updateObj.getCdo().getUSER_NAME()!=null){
    		logger.info("[TWITTER] username ::"+updateObj.getCdo().getUSER_NAME());
    		name = URLEncoder.encode(updateObj.getCdo().getUSER_NAME(), "UTF-8");
    		out.write("name="+name);
    	}
    	if(updateObj.getCdo().getBIO()!=null){
    		logger.info("[TWITTER] bio ::"+updateObj.getCdo().getBIO());
    		description =  URLEncoder.encode(updateObj.getCdo().getBIO(), "UTF-8");
    		out.write("&description="+description);
    	}
        //out.write("name=" + name +"&url="+web+"&location="+location+"&description="+description);
        out.close();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        connection.getInputStream()));
        String response;
        while ((response = in.readLine()) != null) {
        	logger.info("[TWITTER] response ::"+response);
        }
        in.close();

    }
	
	public void updateStatus(IUpdate updateObj, String userName, String password) {
		URL url = null;
		try {
			url = new URL("https://twitter.com/statuses/update.xml");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		URLConnection connection = null;
		try {
			connection = url.openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		connection.setDoInput(true);
		connection.setDoOutput(true);
		connection.setUseCaches(false);

		String authorization = userName + ":" + password;
		Base64 en = new Base64();
		String encoded = new String(en.encode(authorization.getBytes())).trim();
		connection.setRequestProperty("Authorization", "Basic " + encoded);

		OutputStreamWriter out = null;
		try {
			out = new OutputStreamWriter(connection.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		}
		try {
			out.write("status=" + URLEncoder.encode(updateObj.getCdo().getSTATUS(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(connection
					.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String response;
		try {
			while ((response = in.readLine()) != null) {
				// System.out.println(response);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	@Override
	public String getServiceName() {
		// TODO Auto-generated method stub
		return serviceName;
	}
}
